package org.xurui.bsj.protocol.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AesUtils {
    public static String aes128CbcEncrypt(byte[] aesKey,byte[] aesIv,byte[] content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(aesIv);

        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        // AES加密/CBC模式/PKCS5Padding填充方式（默认）
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);
        byte[] encData = cipher.doFinal(content);

        // base64
        Base64.Encoder encoder = Base64.getEncoder();
        String encodedText = encoder.encodeToString(encData);
        return encodedText;
    }

    public static String aes128CbcDecrypt(byte[] aesKey,byte[] aesIv,byte[] content) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(aesIv);

        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        // AES加密/CBC模式/PKCS5Padding填充方式（默认）
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        int j = cipher.getBlockSize();
        // 初始化
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);
        byte[] encData = cipher.doFinal(content);

        String text = new String(encData,"utf-8");
        return text;
    }
}
